package org.hydrakyoufeng.stuplatform.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.hydrakyoufeng.stuplatform.dto.UserDTO;
import org.hydrakyoufeng.stuplatform.dto.UserListDTO;
import org.hydrakyoufeng.stuplatform.service.UserService;
import org.hydrakyoufeng.stuplatform.vo.UserListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("user")
@Tag(name = "用户")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("queryList")
    public ResponseEntity queryList(@RequestBody UserListDTO userListDTO) throws Exception {
        return ResponseEntity.ok(userService.queryList(userListDTO));
    }

    @PostMapping("insert")
    public ResponseEntity insert(@RequestBody UserDTO userDTO) throws Exception {
        return ResponseEntity.ok(userService.insert(userDTO));
    }

    @PostMapping("update")
    public ResponseEntity update(@RequestBody UserDTO userDTO) throws Exception {
        return ResponseEntity.ok(userService.update(userDTO));
    }

    @DeleteMapping("delete/{id}")
    public ResponseEntity delete(@PathVariable("id") Integer id) throws Exception {
        return ResponseEntity.ok(userService.delete(id));
    }

    /**
     * 导出excel
     * @param userListDTO
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("getExcel")
    public void getExcel(@RequestBody UserListDTO userListDTO, HttpServletResponse response) throws Exception {
        String fileName = "用户列表";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileNameEncode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameEncode + ".xlsx");
        List<UserListVO> list = userService.getExcel(userListDTO);
        EasyExcel.write(response.getOutputStream())
                .head(UserListVO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(fileName)
                .doWrite(list);
    }
}
